<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <el-input v-model="form.account_name" class="w-40" placeholder="账号名称"></el-input>
        <VCascader v-model="form.purchase_account_id" placeholder="采购人员" filterable clearable checkStrictly style="min-width: 160px" />
        <VSelect v-model="form.account_type" :options="options.account_type || []" style="min-width: 160px" multiple collapse-tags clearable filterable placeholder="账号类型" />
        <VGroup>
          <div class="v-group-item">更新时间</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/settings/account/add" type="primary" @click="create(tableRef)"><i class="dk-iconfont icon-Plus" />添加
        </VButton>
        <VButton auth="/purchase/settings/account/status" :loading="loadings.start" @click="handleBatch('start')">
          <VStatus :value="true" />
        </VButton>
        <VButton auth="/purchase/settings/account/status" :loading="loadings.stop" @click="handleBatch('stop')">
          <VStatus :value="false" />
        </VButton>
        <VButton auth="/purchase/settings/account/renewal" :loading="loadings.update1688" class="ml-auto" @click="update1688">更新1688账号信息</VButton>
        <VExport auth='/purchase/settings/account/derive' mainKey="pa_id" url="/v1/purchase-config/purchase-account/export" name="account" :tableRef="tableRef" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import { getOption } from '@/api/public'
import { ElMessage } from 'element-plus'
import { on, off } from "@/utils/dom"

const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
getOption({ type: 'purchase_account' }).then(res => {
  options.value = res.data
})


// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const pa_ids = selection.map(d => d.pa_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    start: () => {
      showLoading()
      api.status({ pa_ids, status: 1 }).then(res => {
        query()
        ElMessage({ type: 'success', message: '操作成功!' })
      }).finally(closeLoading)
    },
    stop: () => {
      showLoading()
      api.status({ pa_ids, status: 2 }).then(res => {
        query()
        ElMessage({ type: 'success', message: '操作成功!' })
      }).finally(closeLoading)
    },
  }
  handle[name]()
}

// 更新1688
const update1688 = () => {
  loadings.update1688 = true
  api.update1688().then(() => {
    ElMessage.success('更新成功')
    query()
  }).finally(() => {
    loadings.update1688 = false
  })
}

// 账号授权
const handleMessage = ({ data }) => {
  if (data) {
    ElMessage.success('授权成功')
    query()
  } else {
    ElMessage.error('授权失败')
  }
  off(window, 'message', handleMessage)
}
const auth = (pa_id, rowIndex) => {
  loadings['auth' + rowIndex] = true
  api.auth({ pa_id }).then(res => {
    window.open(
      res.data.auth_url,
      '_blank',
      'height=700, width=1200, top=200, left=300,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'
    )
    on(window, 'message', handleMessage)
  }).finally(() => {
    loadings['auth' + rowIndex] = false
  })
}

// 列表配置
const tableOptions = reactive({
  formConfig: {
    data: {
      account_name: '',
      purchase_account_id: '',
      account_type: [],
      dateRange: { type: 'update_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    { type: 'seq', title: '编号', fixed: 'left', width: 60 },
    {
      field: 'platform_type_name', title: '平台类型', width: 100, slots: {
        default: ({ row }) => <VText value={row.platform_type_name} />
      }
    },
    {
      field: 'account_name', title: '账号名称', minWidth: 180, slots: {
        default: ({ row }) => <VText value={row.account_name} />
      }
    },
    {
      field: 'purchase_account', title: '对应采购人员', width: 140, slots: {
        default: ({ row }) => <VText value={row.purchase_account} line={2} />
      }
    },
    {
      field: 'alipay_account', title: '下单支付宝账号', width: 180, slots: {
        default: ({ row }) => <VText value={row.alipay_account || '-'} />
      }
    },
    {
      field: 'account_type_name', title: '账号类型', width: 100, slots: {
        default: ({ row }) => <VText value={row.account_type_name} />
      }
    },
    {
      field: 'company_id_name', title: '公司主体', minWidth: 140, slots: {
        default: ({ row }) => <VText value={row.company_id_name} line={2} />
      }
    },
    {
      field: 'create_user', title: '添加人', width: 120, slots: {
        default: ({ row }) => <VText value={row.create_user} />
      }
    },
    {
      field: 'update_time', title: '更新时间', width: 170, slots: {
        default: ({ row }) => <VText value={row.update_time} />
      }
    },
    {
      field: 'auth_status_name', title: '授权状态', width: 100, slots: {
        default: ({ row }) => <VStatus value={row.auth_status_name === '已授权'} auth={true} />
      }
    },
    {
      field: 'status_name', title: '状态', width: 70, slots: {
        default: ({ row }) => <VStatus value={row.status_name === '启用'} />
      }
    },
    {
      title: '操作', width: 150, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { pa_id } = row
          return <div class='nm flex gap-2'>
            <VButton auth="/purchase/settings/account/edit" link type="primary" onClick={() => addRef?.value.open(pa_id)}>编辑</VButton>
            <VButton auth="/purchase/settings/account/accredit" link type="primary" loading={loadings['auth' + rowIndex]} onClick={() => auth(pa_id, rowIndex)}>授权</VButton>
            <VButton auth="/purchase/settings/account/logs" link type="primary" onClick={() => logRef?.value.open({ log_type: 'purchase_account', pa_id })}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  